package mx.edu.itesm.tps.proyecto.validator;

import java.util.Properties;

import javax.mail.Session;
import javax.mail.Store;

import mx.edu.itesm.tps.proyecto.criteria.LoginCriteria;

import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

public class LoginCriteriaValidator implements Validator {

    Properties props = new Properties();

    public boolean supports(Class clazz) {
        return clazz.equals(LoginCriteria.class);
    }

    public void validate(Object obj, Errors errors) {
        LoginCriteria query = (LoginCriteria) obj;

        if (!StringUtils.hasText(query.getUserName()) && !StringUtils.hasText(query.getPassWord())) {
            errors.reject("noCriteria", "Please provide valid search criteria");
        } else if (!validInfo(query)) {
            errors.reject("noCriteria", "Invalid login info");
        }
    }

    public boolean validInfo(LoginCriteria query) {
        Session session;
        Store store;
        boolean output = false;

        try {
            session = Session.getDefaultInstance(props, null);
            store = session.getStore("pop3");
        } catch (Exception e) {
            e.printStackTrace();

            return false;
        }

        try {
            store.connect("itesm.mx", query.getUserName(), query.getPassWord());
            output = true;
        } catch (Exception e) {
            output = false;
        }

        try {
            store.close();
        } catch (Exception e) {
        }

        return output;
    }
}
